package com.lsy.clearssm.controller;

import com.lsy.clearssm.common.JsonResult;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

@RestController
@CrossOrigin
public class UploadController {

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public Map<String, Object> upload(MultipartFile multipartFile, HttpServletRequest request) throws IOException {
        String originalFilename = multipartFile.getOriginalFilename();
        System.out.println("originalFilename:"+originalFilename);
        // 从原始文件名中获取后缀,作为新添加的文件的文件名后缀(匹配)
        String subfix = originalFilename.substring(originalFilename.indexOf(".")+1);
        System.out.println("subfix:"+subfix);
        // 使用UUID作为文件名,保证服务器中存放的文件名唯一

        String targetFile = UUID.randomUUID().toString().replace("-","")+"."+subfix;
        System.out.println("targetFile:"+targetFile);

        // 通过request获取当前程序的根路径"/"
        String path = request.getSession().getServletContext().getRealPath("/");
        String fileName = path+"uploadImg/"+targetFile;
        System.out.println("fileName:"+fileName);

        // 构建文件对象
        File uploadFile = new File(fileName);

        // 核心操作(含有异常操作, 利用异常设定状态码(和前端约定)
        // 此处应当和ExceptionController结合, 当try执行成功则设定状态码0
        // 出现异常则设定其他
        // 再将异常信息结合BusinessException抛出, 交给ExceptionController处理
        try {
            multipartFile.transferTo(uploadFile);
        }
        catch (IOException e) {
            throw e;
        }

        JsonResult jsonResult = new JsonResult();

        jsonResult.setCode("2000");
        // 返回服务器保存后的文件名
        jsonResult.setField("fileName", targetFile);
        return jsonResult.getMap();
    }
}
